package de.gbeine.java.ebookmanager.tag;

import java.util.ArrayList;
import java.util.List;

import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;

final class TagRepresenter extends Representer {

    /**
     * Create a new TagRepresenter.
     */
    public TagRepresenter() {
        this.representers.put(Tag.class, new RepresentTag());
    }

    private class RepresentTag implements Represent {
        /**
         * {@inheritDoc}
         */
        public Node representData(final Object data) {
            final Tag tag = (Tag) data;

            final List<NodeTuple> nodeTuples = new ArrayList<NodeTuple>();

            final ScalarNode keyNode = (ScalarNode) representScalar(org.yaml.snakeyaml.nodes.Tag.STR, "name");
            final ScalarNode valueNode = (ScalarNode) representScalar(org.yaml.snakeyaml.nodes.Tag.STR, tag.getName());
            nodeTuples.add(new NodeTuple(keyNode, valueNode));

            if (tag.iterator().hasNext()) {
                final List<Node> childNodes = new ArrayList<Node>();
                for (Tag subTag : tag) {
                    childNodes.add(TagRepresenter.this.represent(subTag));
                }
                final ScalarNode childrenKeyNode = (ScalarNode) representScalar(org.yaml.snakeyaml.nodes.Tag.STR, "subtags");
                final SequenceNode childrenValueNode = new SequenceNode(org.yaml.snakeyaml.nodes.Tag.SEQ, childNodes, false);

                nodeTuples.add(new NodeTuple(childrenKeyNode, childrenValueNode));
            }

            return new MappingNode(new org.yaml.snakeyaml.nodes.Tag("!tag"), nodeTuples, false);
        }
    }

}
